package com.hong.qrpc.server;

import com.hong.qrpc.RequestHandler;
import com.hong.qrpc.TransportServer;
import com.hong.qrpc.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author HQT
 * @Date 2022/7/10 10:16
 */
@Slf4j
public class HttpTransportServer implements TransportServer {
    private RequestHandler handler;
    /**
     * jetty的server
     */
    private Server server;
    private int port;

    @Override
    public void init(int port, int protoType, RequestHandler handler) {
        this.handler = handler;
        //在这个端口开一个jetty服务器
        this.server = new Server(port);
        log.info("init net client port:{}  protoType:{}   handler:{}", this.port, protoType, handler);
        //使用servlet接收请求
        ServletContextHandler ctx = new ServletContextHandler();
        server.setHandler(ctx);
        //处理网络请求的抽象对象
        ServletHolder servletHolder = new ServletHolder(new RequestServlet());
        //处理所有的请求
        ctx.addServlet(servletHolder, "/*");
    }

    @Override
    public void start() {
        try {
            server.start();
            port = server.getURI().getPort();
            synchronized (this) {
                this.notifyAll();
            }
            //此处使线程阻塞
            server.join();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public void stop() {
        try {
            server.stop();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public int getPort() {
        return port;
    }

    /**
     * 处理请求的自定义servlet
     */
    class RequestServlet extends HttpServlet {
        /**
         * 只接收post请求
         *
         * @param req  request请求对象
         * @param resp 响应对象
         */
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            log.info("client connection");
            String serializationType = req.getHeader("serializationType");
            if (StringUtils.isEmpty(serializationType)) {
                throw new IllegalArgumentException("unsupported serialization type");
            }
            InputStream inputStream = req.getInputStream();
            OutputStream outputStream = resp.getOutputStream();
            if (handler != null) {
                handler.onRequest(inputStream, outputStream, Integer.parseInt(serializationType));
            }
            outputStream.flush();
        }
    }
}
